var treeID = "menuTree";

var customTempleteType =
    [
        // {"code": "null", "incrementId": 1, "value": "", "version": 1, "order": 0},
        // {"code": "list", "incrementId": 2, "value": "列表", "version": 1, "order": 1},
        // {"code": "edit","incrementId": 3,"value": "编辑", "version": 1, "order": 2},
        {"code": "list-edit", "incrementId": 4, "value": "列表+编辑", "version": 1, "order": 3},
        // {"code": "catalogue", "incrementId": 5, "value": "目录", "version": 1, "order": 4},
        // {"code": "fullScreen", "incrementId": 6, "value": "全局(无头无左边栏)", "version": 1, "order": 5},
        // {"code": "Single", "incrementId": 7, "value": "单页(有头有左边栏不用传病历号)", "version": 1, "order": 6},
        // {"code": "null", "incrementId": 1, "value": "", "version": 1, "order": 7}
    ]

var setting = {
    simpleData: {
        enabled: true
    },
    view: {
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        selectedMulti: false
    },
    edit: {
        enable: true,
        editNameSelectAll: true,
        showRemoveBtn: showRemoveBtn,
        showRenameBtn: showRenameBtn
    },
    data: {
        key: {
            name: "customName"
        },
        simpleData: {
            enable: true,
            idKey: "customId",
            pIdKey: "ext1",
            rootPId: 0
        }
    },

    callback: {

        onClick: function (event, treeId, treeNode) {
            // Page.Event.getMenuShortNameList();
            selectNodeId = treeNode.customId
            $('.moduleSelect  ul').empty();/*清空木板选择*/
            $('button').attr('disabled', true);
            $('#Extra3,#Extra4,#Extra5').attr('disabled', true);
            $('#moduleName').text(''); /*清空模块名称*/
            /*判断是否满足内容在单模块文件夹内*/
            if (treeNode.getParentNode()) {
                var dataArr = [];
                if (!treeNode.children) {
                    if (treeNode.getPreNode() && treeNode.getPreNode().children) {
                        dataArr = [treeNode]
                    } else {
                        dataArr = treeNode.getParentNode().children
                    }
                } else {
                    dataArr = []
                    treeNode.children.forEach(function (item, i) {/*获取文件夹下单文件*/
                        if (!item.children) {
                            dataArr.push(item)
                        }
                    })
                }
                dataArr.forEach(function (item, i) {
                    $('.moduleSelect  ul').append(`<li creater="${item.creater || ''}" createrTime="${item.createrTime || ''}" customId="${item.customId || ''}" parentId="${item.ext1 || ''}">${item.customName || ''}</li>`)
                })
                $('#add').removeAttr('disabled');
                $('#Extra3,#Extra4,#Extra5').removeAttr('disabled');
                $('.moduleSelect').find(`li[customId=${treeNode.customId}]`).click()
            }
            let preTree = treeNode;
            let moduleNameArr = [preTree.customName];
            let moduleName = '';
            for (var i = 1; i > 0; i++) { /*模块名称源排序*/
                if (preTree.getParentNode()) {
                    preTree = preTree.getParentNode();
                    moduleNameArr.push(preTree.customName)
                } else {
                    break
                }
            }
            /*获取模块名称*/
            moduleNameArr.reverse().forEach(function (item, i) {
                moduleName += item + '→';
            })
            $('#moduleName').text(moduleName.slice(0, moduleName.length - 1));
            $('#menuId').val(treeNode.customId);
            $('#menuName').val(treeNode.customName).removeAttr('disabled');
            $('#Extra1').val(treeNode.ext1);
            $('#Extra2').val(treeNode.ext2 || '');
            $('#Extra3').val(treeNode.ext3 || '');
            $('#Extra4').val(treeNode.ext4 || '');
            $('#Extra5').val(treeNode.ext5 || '');
            $('#save,#delete').removeAttr('disabled')
        },

        beforeDrag: beforeDrag,
        beforeEditName: beforeEditName,
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        onRemove: onRemove,
        onRename: onRename

        // beforeRemove: function (treeId, treeNode) {
        //     confirm("确认删除 节点 -- " + treeNode.customName + " 吗？");
        //     $.fn.zTree.init($('#menuTree'), setting, resultList);
        //
        //     // layer.confirm("确定删除吗?",
        //     //     {
        //     //         btn: ["确定", "取消"],
        //     //         title: "提示",
        //     //         icon: 7
        //     //     },
        //     //     function () {
        //     //         var lock = false;
        //     //         var params = {
        //     //             customId: treeNode.customId,
        //     //             del: 1
        //     //         }
        //     //         // updateAjax(params, 'PUT', 'deleteCoin', false, lock)
        //     //         if (lock) return false
        //     //     }, function () {
        //     //         layer.closeAll();
        //     //         $.fn.zTree.init($('#menuTree'), setting, resultList);
        //     //     });
        // }

    }
};


var log, className = "dark";

function beforeDrag(treeId, treeNodes) {
    return false;
}

function beforeEditName(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
    var zTree = $.fn.zTree.getZTreeObj(treeID);
    zTree.selectNode(treeNode);
    setTimeout(function () {
        if (confirm("进入节点 -- " + treeNode.customName + " 的编辑状态吗？")) {
            setTimeout(function () {
                zTree.editName(treeNode);
            }, 0);
        }
    }, 0);
    return false;
}

function beforeRemove(treeId, treeNode) {
    className = (className === "dark" ? "" : "dark");
    showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
    var zTree = $.fn.zTree.getZTreeObj(treeID);
    zTree.selectNode(treeNode);
    return confirm("确认删除 节点 -- " + treeNode.customName + " 吗？");
}

function onRemove(e, treeId, treeNode) {
    showLog("[ " + getTime() + " onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
}

function beforeRename(treeId, treeNode, newName, isCancel) {
    className = (className === "dark" ? "" : "dark");
    showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>" : ""));
    if (newName.length == 0) {
        setTimeout(function () {
            var zTree = $.fn.zTree.getZTreeObj(treeID);
            zTree.cancelEditName();
            alert("节点名称不能为空.");
        }, 0);
        return false;
    }
    return true;
}

function onRename(e, treeId, treeNode, isCancel) {
    showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>" : ""));
}

function showRemoveBtn(treeId, treeNode) {
    return !treeNode.isFirstNode;
}

function showRenameBtn(treeId, treeNode) {
    return !treeNode.isLastNode;
}

function showLog(str) {
    if (!log) log = $("#log");
    log.append("<li class='" + className + "'>" + str + "</li>");
    if (log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}

function getTime() {
    var now = new Date(),
        h = now.getHours(),
        m = now.getMinutes(),
        s = now.getSeconds(),
        ms = now.getMilliseconds();
    return (h + ":" + m + ":" + s + " " + ms);
}

var newCount = 1;

function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function () {
        var zTree = $.fn.zTree.getZTreeObj(treeID);
        zTree.addNodes(treeNode, {id: (100 + newCount), pId: treeNode.id, name: "new node" + (newCount++)});
        return false;
    });
};

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
};

function selectAll() {
    var zTree = $.fn.zTree.getZTreeObj(treeID);
    zTree.setting.edit.editNameSelectAll = $("#selectAll").attr("checked");
}

function getMenuTypeList() {
    var triageLevel = customTempleteType;
    var html = '';
    for (var i = 0; i < triageLevel.length; i++) {
        if (i == triageLevel.length - 1) {
            html += "<option value='" + triageLevel[i].code + "' selected='selected'>" + triageLevel[i].value + "</option>";
        } else {
            html += "<option value='" + triageLevel[i].code + "'>" + triageLevel[i].value + "</option>";
        }
    }
    $('#Extra3').html(html);
}


function getList() {
    var resultList;
    $.ajax({
        url: '/template/cdStructuredCustom/customEmrList/query',
        type: 'GET',
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (data) {
            if (data.state == 200 && data.results) {
                resultList = data.results.rest
            } else {
                top.layer.alert(data.msg);
            }
        },
        error: function (res) {
            top.$(".layui-layer-btn0").css("pointer-events", "");
            top.layer.alert("服务器连接超时!");
            lock = true;
        }
    });
    return resultList
}


function updateAjax(params, type, way, async, lock) {
    $.ajax({
        url: '/template/cdStructuredCustom',
        type: type,
        data: JSON.stringify(params),
        contentType: 'application/json;charset=utf-8',
        async: async || true,
        success: function (data) {
            if (data.state == 200) {
                switch (way) {
                    case "delete":
                        top.layer.msg("删除成功！");
                        break;
                    case "deleteCoin":
                        top.layer.msg("删除成功");
                        break;
                    case "save":
                        top.layer.msg("保存成功");
                        break;
                    case "saveIcon":
                        top.layer.msg("新增成功");
                        break;
                    default:
                        break;
                }
                var zTree = $.fn.zTree.getZTreeObj(treeID);
                $.fn.zTree.init($("#" + treeID), setting, getList());
                // $.fn.zTree.init($("#"+treeID), setting, resultList);
                zTree.selectNode(zTree.getNodeByParam('customId', selectNodeId))/*选择树节点*/
            } else {
                switch (way) {
                    case "delete":
                        top.layer.error("删除失败！", res.msg);
                        break;
                    case "delete":
                        top.layer.error("删除失败！", res.msg);
                        lock = true;/*树形删除锁*/
                        break;
                    case "save":
                        top.layer.error("保存失败");
                        break;
                    case "saveIcon":
                        top.layer.error("新增失败");
                        lock = true;/*树形新增锁*/
                        break;
                    default:
                        break;
                }
            }
        },
        error: function (res) {
            top.$(".layui-layer-btn0").css("pointer-events", "");
            top.layer.alert("服务器连接超时!");
            lock = true;
        }

    });
    return lock
}

function judgeIfExistSameShortName(params) {
    var count = 0;
    $.ajax({
        url: '/template/cdStructuredCustom/judgeIfExistSameShortName',
        type: 'GET',
        data: params,
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (data) {
            count = data.results.result
        }
    });
    return count;
}


$(document).ready(function () {
    getMenuTypeList();
    $.fn.zTree.init($("#" + treeID), setting, resultList);
    // $.fn.zTree.init($("#treeID"), setting, zNodes);
    // $("#selectAll").bind("click", selectAll);


    /*编辑操作*/
    $('#edit').click(function (e) {
        var id = $('#menuId').val();
        //以下的prefixKey用作redis的key，如果有shortName则优先取，否则就去取菜单编号customId，可作为唯一key
        var prefixKey = $('#Extra5').val() ? $('#Extra5').val() : id;
        window.location.href = "/template/cdStructuredCustom/customEmr?customId=" + id + "&customName=" + $('#menuName').val() + "&prefixKey=" + prefixKey;
        // window.open("/template/cdStructuredCustom/customEmr?customId=" + id + "&customName=" + $('#menuName').val() + "&prefixKey=" + prefixKey);

    });
    /*新增操作*/
    $('#add').click(function () {
        $('input').not('#Extra1').val('');
        $('.moduleSelect  ul li').removeClass('moduleSelect');
        $('.moduleSelect  ul').append('<li>新模板</li>');
        $('#menuName').val('新模板').removeAttr('disabled');
    });
    /*增加医院操作*/
    $('#addRootNode').click(function () {
        var treeObj = $.fn.zTree.getZTreeObj(treeID);
        var nodes = treeObj.getNodes();
        var lastMenuOrder;
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].isLastNode == true) {
                lastMenuOrder = nodes[i].menuOrder;
            }
        }
        var newNodeOrder = lastMenuOrder + 1;
        var newNode = {customId: 0, del: 0, customName: "xx目录", ext1: 0};
        var params = {
            customId: 0,
            customName: "xx目录",
            del: "0",
            ext1: "0",
        }
        var lock = false;
        updateAjax(params, 'POST', 'saveIcon', false, lock);
        if (!lock) treeObj.addNodes(null, newNode)
    })
    /*刷新操作*/
    $('#refresh').click(function () {
        $.ajax({
            url: '/template/cdStructuredCustom/refreshRedis',
            type: "GET",
            contentType: 'application/json;charset=utf-8',
            success: function (data) {
                if (data.state == 200) {
                    top.layer.msg("模板缓存清除成功！");
                } else {
                    top.layer.error("发生异常，缓存可能清除失败！");
                }
            }
        });
    })
    /*保存操作*/
    $('#save').click(function () {
        if ($('#menuId').val() && $('#menuId').val() != 0) {
            var type = 'PUT'
        } else {
            var type = 'POST'
        }
        var params = {
            customId: $('#menuId').val(),
            customName: $('#menuName').val(),
            del: '0',
            ext1: $('#Extra1').val(),
            ext2: $('#Extra2').val(),
            ext3: $('#Extra3').val(),
            ext4: $('#Extra4').val(),
            ext5: $('#Extra5').val(),
        }
        if ($('#Extra3').val()) {
            switch ($('#Extra3').val()) {
                case "list":
                    params.ext2 = "/customPage/list";
                    break;
                case "edit":
                    params.ext2 = "/customPage/edit";
                    break;
                case "list-edit":
                    params.ext2 = "/customPage/customPageIndex";
                    break;
                case "fullScreen":
                    params.ext2 = "/customPage/fullScreen";
                    break;
                default:
                    params.ext2 = "";
                    break;
            }
        }
        if (params.ext5 != "") {
            var count = judgeIfExistSameShortName(params);
            debugger;
            if (count > 0) {
                top.layer.error("已经存在相同的菜单简称，请检查是否重复后再保存！");
                return false;
            }
        }
        if (type == 'PUT') {
            if (params.ext2 != "") {
                if (params.ext5 != "") {
                    params.ext2 += "?menuShortName=" + params.ext5;
                } else {
                    params.ext2 += "?customId=" + params.customId;
                }
            }
            $.ajax({
                url: '/template/cdStructuredCustom/justPut',
                type: type,
                data: JSON.stringify(params),
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                    if (data.state == 200) {
                        top.layer.msg("保存成功");
                        var zTree = $.fn.zTree.getZTreeObj(treeID);
                        $.fn.zTree.init($("#" + treeID), setting, getList());
                        // $.fn.zTree.init($("#"+treeID), setting, resultList);
                        zTree.selectNode(zTree.getNodeByParam('customId', selectNodeId))/*选择树节点*/
                    } else {
                        top.layer.error("保存失败");
                    }
                },
                error: function (res) {
                    top.$(".layui-layer-btn0").css("pointer-events", "");
                    top.layer.alert("服务器连接超时!");
                    lock = true;
                }

            });
        } else {
            updateAjax(params, type, 'save')
        }
    })
    /*删除操作*/
    $('#delete').click(function () {

        // var params = {
        //     customId: $('#menuId').val(),
        //     del: "1"
        // };
        // updateAjax(params, 'PUT', 'delete')
        layer.confirm("确定删除吗?",
            {
                btn: ["确定", "取消"],
                title: "提示",
                icon: 7
            },
            function () {
                var params = {
                    customId: $('#menuId').val(),
                    del: "1"
                };
                updateAjax(params, 'PUT', 'delete')
            });
    })


    $('#go').click(function () {
       var url = $('#Extra2').val();
       // console.log("url",url);
        window.open(url);
    })


    /*点击模板操作*/
    $('body').on('click', '.moduleSelect li', function () {
        $(this).addClass('moduleSelect').siblings().removeClass('moduleSelect');
        $('button').removeAttr('disabled');
        var zTree = $.fn.zTree.getZTreeObj(treeID);
        zTree.selectNode(zTree.getNodeByParam('customId', $(this).attr('customid')))/*选择树节点*/
        $('#menuId').val($(this).attr('customid'));
        $('#menuName').val($(this).text()).removeAttr('disabled');
        $('#Extra1').val($(this).attr('parentid'));
        $('#createName').val($(this).attr('creater')).removeAttr('disabled');
        $('#createTime').val($(this).attr('creatertime'));
    })

});